package com.haoc.lostandfound.auth;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.haoc.lostandfound.R;
import com.haoc.lostandfound.adapter.LinkAdapter;
import com.haoc.lostandfound.cloudstorage.CloudStorage;
import com.haoc.lostandfound.entity.LinkEntity;
import com.haoc.lostandfound.view.CircleTransform;
import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.auth.AGConnectUser;
import com.huawei.agconnect.auth.ProfileRequest;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AuthMainActivity extends Activity implements View.OnClickListener {
    ImageView imgViewPhoto;
    TextView txtViewUid;
    TextView txtViewNickName;
    TextView txtViewEmail;
    TextView txtViewPhone;
    Button btnUpdateName;
    String uid;
    File file = null;
    private static final int CROP_PHOTO = 12;// 裁剪图片
    private static final int LOCAL_CROP = 13;// 本地图库
    CloudStorage cloudStorage = CloudStorage.getInstance();
    public static AuthMainActivity authMainActivity = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auth_main);
        initView();
        showUserInfo();
        authMainActivity = this;
    }

    private void initView() {
        imgViewPhoto = findViewById(R.id.imgView_photo);
        imgViewPhoto.setOnClickListener(this);
        txtViewUid = findViewById(R.id.txtView_uid);
        txtViewNickName = findViewById(R.id.txtView_NickName);
        txtViewEmail = findViewById(R.id.txtView_email);
        txtViewPhone = findViewById(R.id.txtView_phone);
        btnUpdateName = findViewById(R.id.btn_update_name);
        btnUpdateName.setOnClickListener(this);

        findViewById(R.id.imgView_back).setOnClickListener(this);
        findViewById(R.id.btn_link).setOnClickListener(this);
        findViewById(R.id.imgView_settings).setOnClickListener(this);
    }

    private void showUserInfo() {
        AGConnectUser agConnectUser = AGConnectAuth.getInstance().getCurrentUser();
        uid = agConnectUser.getUid();
        String nickname = agConnectUser.getDisplayName();
        String email = agConnectUser.getEmail();
        String phone = agConnectUser.getPhone();
        if (phone != null) {
            phone = phone.substring(4);
        }
        String photoUrl = agConnectUser.getPhotoUrl();
        txtViewUid.setText(uid);
        txtViewNickName.setText(nickname);
        txtViewEmail.setText(email);
        txtViewPhone.setText(phone);
        if (!TextUtils.isEmpty(photoUrl)) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Picasso.with(AuthMainActivity.this)
                            .load(photoUrl)
                            .transform(new CircleTransform())
                            .networkPolicy(NetworkPolicy.NO_CACHE)
                            .memoryPolicy(MemoryPolicy.NO_CACHE)
                            .into(imgViewPhoto);
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imgView_photo:
                // 创建Intent，用于打开手机本地图库选择图片
                Intent intent1 = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // 启动intent打开本地图库
                startActivityForResult(intent1, LOCAL_CROP);
                break;
            case R.id.btn_update_name:
                updateDisplayName();
                break;
            case R.id.btn_link:
                link();
                break;
            case R.id.imgView_back:
                finish();
                break;
            case R.id.imgView_settings:
                startActivity(new Intent(this, SettingsActivity.class));
                break;
        }
    }

    private void link() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_link, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();
        ListView listView = view.findViewById(R.id.list_view);
        List<LinkEntity> linkEntityList = initLink();
        LinkAdapter linkAdapter = new LinkAdapter(dialog.getContext(), R.layout.list_link_item, linkEntityList, new LinkClickCallback() {
            @Override
            public void click() {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        listView.setAdapter(linkAdapter);
        dialog.show();
    }

    public interface LinkClickCallback {
        void click();
    }

    private List<LinkEntity> initLink() {
        List<LinkEntity> linkEntityList = new ArrayList<>();
        linkEntityList.add(new LinkEntity("华为帐号", R.mipmap.huawei, HWIDActivity.class));
        linkEntityList.add(new LinkEntity("手机号", R.drawable.ic_phone, PhoneActivity.class));
        linkEntityList.add(new LinkEntity("邮箱", R.drawable.ic_email, EmailActivity.class));
        return linkEntityList;
    }

    private void updateDisplayName() {
        LinearLayout layout = new LinearLayout(AuthMainActivity.this);
        layout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        layout.setOrientation(LinearLayout.VERTICAL);
        final EditText editText = new EditText(AuthMainActivity.this);
        layout.addView(editText);
        AlertDialog.Builder dialogBuilder =
                new AlertDialog.Builder(AuthMainActivity.this).setTitle("设置昵称");
        dialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 输入昵称
                String data = editText.getText().toString().trim();
                if (!TextUtils.isEmpty(data)) {
                    if (AGConnectAuth.getInstance().getCurrentUser() != null) {
                        // 构造ProfileRequest对象
                        ProfileRequest userProfile = new ProfileRequest.Builder()
                                .setDisplayName(data)
                                .build();
                        // 更新当前用户的个人信息（昵称）
                        AGConnectAuth.getInstance().getCurrentUser().updateProfile(userProfile)
                                .addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        showUserInfo();
                                        Toast.makeText(AuthMainActivity.this, "更新昵称成功", Toast.LENGTH_SHORT).show();
                                    }
                                })
                                .addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(Exception e) {
                                        Toast.makeText(AuthMainActivity.this, "更新昵称失败:" + e, Toast.LENGTH_LONG).show();
                                    }
                                });
                    }
                }
            }
        });
        dialogBuilder.setView(layout);
        dialogBuilder.show();
    }

    /**
     * 调用startActivityForResult方法启动一个intent后，
     * 可以在该方法中拿到返回的数据
     * 展示图片
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case LOCAL_CROP:// 系统图库
                if (resultCode == RESULT_OK) {
                    // 创建intent用于裁剪图片
                    Intent intent1 = new Intent("com.android.camera.action.CROP");
                    // 获取图库所选图片的uri
                    Uri uri = data.getData();
                    intent1.setDataAndType(uri, "image/*");
                    //  设置裁剪图片的宽高
                    intent1.putExtra("outputX", 300);
                    intent1.putExtra("outputY", 300);
                    // 裁剪后返回数据
                    intent1.putExtra("return-data", true);
                    // 启动intent，开始裁剪
                    startActivityForResult(intent1, CROP_PHOTO);
                }
                break;
            case CROP_PHOTO:// 裁剪后展示图片
                if (resultCode == RESULT_OK) {
                    // 展示图库中选择裁剪后的图片
                    if (data != null) {
                        // 根据返回的data，获取Bitmap对象
                        Bitmap bitmap = data.getExtras().getParcelable("data");
                        // 保存到本地后上传至云存储服务器
                        file = saveImage(bitmap);
                        if (file != null) {
                            cloudStorage.uploadFile(file);
                        }
                    }
                }
                break;
        }
    }

    /**
     * 保存Bitmap到本地
     *
     * @param bmp
     * @return
     */
    private File saveImage(Bitmap bmp) {
        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/AGCSdk/");
        if (!dir.exists()) {
            dir.mkdir();
        }
        String fileName = "crop" + uid + ".jpg";
        File file = new File(dir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            return file.getAbsoluteFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新头像
     *
     * @param data
     */
    public void updateAvatar(String data) {
        if (AGConnectAuth.getInstance().getCurrentUser() != null) {
            // 构造ProfileRequest对象
            ProfileRequest userProfile = new ProfileRequest.Builder()
                    .setPhotoUrl(data)
                    .build();
            // 更新当前用户的个人信息（头像）
            AGConnectAuth.getInstance().getCurrentUser().updateProfile(userProfile)
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            showUserInfo();
                            Toast.makeText(AuthMainActivity.this, "更新头像成功", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(Exception e) {
                            Toast.makeText(AuthMainActivity.this, "更新头像失败:" + e, Toast.LENGTH_LONG).show();
                        }
                    });
        }
    }
}